前端那些事

vuePress-theme-reco chenpeng    2020 - 2021
前端那些事 前端那些事

Choose mode

  • dark
  • auto
  • light
首页
文章目录
  • Browser
  • CSS
  • ES6
  • JavaScript
  • Network
  • TypeScript
  • Vue
  • Vue3
  • Webpack
标签
时间轴
GitHub
author-avatar

chenpeng

85

Article

25

Tag

首页
文章目录
  • Browser
  • CSS
  • ES6
  • JavaScript
  • Network
  • TypeScript
  • Vue
  • Vue3
  • Webpack
标签
时间轴
GitHub
  • JS-API

    • new的原理
    • new和Object.create的区别
    • bind、call、apply的区别
    • 如何正确判断this的指向
    • 深拷贝与浅拷贝

bind、call、apply的区别

vuePress-theme-reco chenpeng    2020 - 2021

bind、call、apply的区别

chenpeng 2020-11-30 JS API

# 1.bind()

该方法会创建一个函数的实例,其 this 值会被绑定到传给 bind() 函数的值

语法:

var fn = Function.bind(obj, [param1[,param2][,...paramN]])
1

使用场景为函数不需要立即调用,但又想改变函数内部的 this 指向(比如定时器内部的 this)

const btn = document.querySelector('button');
btn.onclick = function () {
    this.disabled = true;
    setTimeout(function () {
        this.disabled  =false;
    }.bind(this), 2000);
}
1
2
3
4
5
6
7

bind() 主要是为了改变函数内部的 this 指向

# 2.apply()

apply() 方法接收两个参数,一个是在其中运行函数的作用域,另一个是参数数组(参数数组可以是数组实例,也可以是 arguments 对象)

语法:

Function.apply(obj, args)
// args将作为参数传递给Function
1
2

使用场景主要与数组有关

1.Math.max 实现得到数组的最大项

const arr = [1,2,3];
console.log(Math.max.apply(Math, arr)); // 也可以使用null,但严格模式下还是要使用Math
// 3
1
2
3

2.Array.prototype.push 实现合并两个数组

const arr1 = [1,2,3];
const arr2 = [4,5,6];
Array.prototype.push.apply(arr1, arr2);
console.log(arr1);
// [1,2,3,4,5,6]
1
2
3
4
5

# 3.call()

call() 方法与 apply() 方法类似,接收参数的方式有些不同,第一个参数为在其中运行函数的作用域,其余参数都直接传递给函数,即传递给函数的参数必须逐个列举出来

语法:

Function.call(obj, [param1[,param2][,...paramN]])
// param参数列表会直接传递给Function
1
2

使用场景是可以实现继承

function Person(name, age) {
    this.name = name;
    this.age = age;
}
function Student(name, age, id) {
    Person.call(this, name, age);
    this.id = id;
}
let s = new Student('张三', 20, '007');
console.log(s);
// Student {name: "张三", age: 20, id: "007"}
1
2
3
4
5
6
7
8
9
10
11